package com.finace.money.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.design.widget.TabLayout;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.finace.money.R;
import com.finace.money.common.Constant;
import com.finace.money.common.util.ACache;
import com.finace.money.common.util.ChooseUtil;
import com.finace.money.common.util.MessageSendUtil;
import com.finace.money.common.util.TabLayoutUtil;
import com.finace.money.common.util.UIUtil;
import com.finace.money.data.bean.BannerBean;
import com.finace.money.data.bean.DealRecordListBean;
import com.finace.money.data.bean.StatusListBean;
import com.finace.money.data.bean.TickBean;
import com.finace.money.di.component.AppComponent;
import com.finace.money.di.component.DaggerMainHomeComponent;
import com.finace.money.di.module.DealRecordModule;
import com.finace.money.di.module.MainHomeModule;
import com.finace.money.interfaces.OnItemClickListener;
import com.finace.money.net.socket.PushReceiver;
import com.finace.money.presenter.DealRecordPresenter;
import com.finace.money.presenter.MainHomePresenter;
import com.finace.money.presenter.contract.DealRecordContract;
import com.finace.money.presenter.contract.MainHomeContract;
import com.finace.money.ui.activity.MyChooseActivity;
import com.finace.money.ui.activity.StatusDetalActivity;
import com.finace.money.ui.activity.WebViewActivity;
import com.finace.money.ui.adapter.AllCompanyAdapter;
import com.finace.money.ui.adapter.HomeMoneyAdapter;
import com.finace.money.ui.adapter.HomeNewsAdapter;
import com.finace.money.ui.adapter.HomeRecordAdapter;
import com.finace.money.ui.adapter.MainViewPagerAdapter;
import com.finace.money.ui.widget.MyListView;
import com.finace.money.ui.widget.WrapContentHeightViewPager;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * Created by zhangpeng on 2017/11/23.
 */

public class MainHomeFragment extends BaseFragment<MainHomePresenter> implements View.OnClickListener,
        MainHomeContract.View, DealRecordContract.View {
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.list_all_company)
    MyListView listAllCompany;
    @BindView(R.id.tab_home)
    TabLayout tabHome;
    @BindView(R.id.tv_all_money)
    TextView tvAllMoney;
    @BindView(R.id.viewPager)
    WrapContentHeightViewPager viewPager;
    @BindView(R.id.tv_home_more)
    TextView tvHomeMore;
    @BindView(R.id.tv_home_choose)
    TextView tvHomeChoose;
    @BindView(R.id.tv_home_advice)
    TextView tvHomeAdvice;
    @BindView(R.id.tv_home_im)
    TextView tvHomeIm;
    @BindView(R.id.tv_home_custom)
    TextView tvHomeCustom;
    @BindView(R.id.banner_home)
    Banner bannerHome;

    private List<StatusListBean> statusLists;
    private List<StatusListBean> showLists;
    private List<BannerBean.RowsBean> mBanners;

    @Inject
    public DealRecordPresenter mDealRecordPresenter;
    private HomeRecordAdapter homeRecordAdapter;
    private HomeNewsAdapter homeNewsAdapter;
    private List<DealRecordListBean.RowsBean> mRows;
    private AllCompanyAdapter mAllCompanyAdapter;

    @Override
    public int setLayout() {
        return R.layout.fragment_home;
    }

    @Override
    public void init() {

        mPresenter.getBanner();
        mDealRecordPresenter.getList(Constant.page_deal_record, "10", "1");
        mDealRecordPresenter.getList(Constant.page_news, "10", "1");
        tvAllMoney.setOnClickListener(this);
        tvHomeMore.setOnClickListener(this);
        tvHomeChoose.setOnClickListener(this);
        tvHomeAdvice.setOnClickListener(this);
        tvHomeIm.setOnClickListener(this);
        tvHomeCustom.setOnClickListener(this);
        initView();
        initViewPager();
        initBanner();
        initListClick();
        tabHome.setupWithViewPager(viewPager);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PushReceiver.ACTION_TICK);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadcastReceiver, intentFilter);
        unregisterReceiver(broadcastReceiver);
        listAllCompany.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (MessageSendUtil.isLogin()) {
                    Intent intent = new Intent(UIUtil.getContext(), StatusDetalActivity.class);
                    intent.putExtra("statusData", showLists.get(position));
                    UIUtil.startActivity(intent);
                }
            }
        });
    }

    private void initBanner() {
        bannerHome.setDelayTime(4000);
        bannerHome.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                Glide.with(context.getApplicationContext())
                        .load(((BannerBean.RowsBean) path).getPic_path())
                        .crossFade()
                        .placeholder(R.drawable.icon_home)
                        .error(R.drawable.icon_home)
                        .into(imageView);
            }
        });
        bannerHome.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (null != mBanners && mBanners.size() > 0) {
                    WebViewActivity.launcher(UIUtil.getContext(), mBanners.get(position).getUrl(), "BANNER");
                }
            }
        });
    }

    private void initView() {
        tabHome.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        tvAllMoney.setVisibility(View.VISIBLE);
                        break;
                    case 1:
                        tvAllMoney.setVisibility(View.GONE);
                        break;
                    case 2:
                        tvAllMoney.setVisibility(View.GONE);
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        statusLists = (List<StatusListBean>) ACache.get(UIUtil.getContext()).getAsObject(PushReceiver.ACTION_LIST);
        showLists = mPresenter.getList(statusLists);
        mAllCompanyAdapter = new AllCompanyAdapter();
        mAllCompanyAdapter.setShowLists(showLists);
        listAllCompany.setAdapter(mAllCompanyAdapter);

        TabLayoutUtil.reflex(tabHome);
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (null != intent) {
                TickBean tickBean = (TickBean) intent.getSerializableExtra(PushReceiver.DATA);
                for (StatusListBean statusListBean : showLists) {
                    if (statusListBean.getM_Body().getM_ProductID().equals(tickBean.getSymbol())) {
                        statusListBean.getM_Body().setTickbean(tickBean);
                        mAllCompanyAdapter.notifyDataSetChanged();
                        return;
                    }
                }
            }
        }
    };

    private void initViewPager() {
        ArrayList<View> views = new ArrayList<>();
        ArrayList<String> titles = new ArrayList<>();
        //昨日交易
        View viewMoney = LayoutInflater.from(UIUtil.getContext()).inflate(R.layout.recycle_view, viewPager, false);
        RecyclerView recyclerViewMoney = viewMoney.findViewById(R.id.recyclerView_home);
        recyclerViewMoney.setLayoutManager(new LinearLayoutManager(UIUtil.getContext(), LinearLayoutManager.VERTICAL, false));
        HomeMoneyAdapter homeMoneyAdapter = new HomeMoneyAdapter();
        recyclerViewMoney.setAdapter(homeMoneyAdapter);
        views.add(viewMoney);
        titles.add(getString(R.string.trading_yestoday));

        //交易攻略
        View viewRecord = LayoutInflater.from(UIUtil.getContext()).inflate(R.layout.recycle_view, viewPager, false);
        RecyclerView recyclerViewRecord = viewRecord.findViewById(R.id.recyclerView_home);
        recyclerViewRecord.setLayoutManager(new LinearLayoutManager(UIUtil.getContext(), LinearLayoutManager.VERTICAL, false));
        homeRecordAdapter = new HomeRecordAdapter();
        recyclerViewRecord.setAdapter(homeRecordAdapter);
        views.add(viewRecord);
        titles.add(getString(R.string.trading_strategy));

        //行业资讯
        View viewNews = LayoutInflater.from(UIUtil.getContext()).inflate(R.layout.recycle_view, viewPager, false);
        RecyclerView recyclerViewNews = viewNews.findViewById(R.id.recyclerView_home);
        recyclerViewNews.setLayoutManager(new LinearLayoutManager(UIUtil.getContext(), LinearLayoutManager.VERTICAL, false));
        homeNewsAdapter = new HomeNewsAdapter();
        recyclerViewNews.setAdapter(homeNewsAdapter);
        views.add(viewNews);
        titles.add(getString(R.string.industry_information));

        MainViewPagerAdapter mainViewPagerAdapter = new MainViewPagerAdapter(views, titles);
        viewPager.setAdapter(mainViewPagerAdapter);
    }

    private void initListClick() {

        homeRecordAdapter.setmListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                WebViewActivity.launcher(UIUtil.getContext(), mRows.get(position).getLink(), "交易攻略");
            }
        });
        homeNewsAdapter.setmListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                WebViewActivity.launcher(UIUtil.getContext(), mRows.get(position).getLink(), "行业资讯");
            }
        });
    }


    @Override
    public void setupAcitivtyComponent(AppComponent appComponent) {

        DaggerMainHomeComponent.builder().appComponent(appComponent).
                mainHomeModule(new MainHomeModule(this))
                .dealRecordModule(new DealRecordModule(this))
                .build().inject(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_all_money:
                break;
            case R.id.tv_home_more:
                Intent intent = new Intent(UIUtil.getContext(), MyChooseActivity.class);
                intent.putExtra("where", "home");
                getActivity().startActivity(intent);

                break;
            case R.id.tv_home_choose:
                int chooseCount = ChooseUtil.getChooseCount();
                if (chooseCount > 0) {
                    Intent intentChoose = new Intent(UIUtil.getContext(), MyChooseActivity.class);
                    getActivity().startActivity(intentChoose);
                } else {
                    UIUtil.showToastSafe(getString(R.string.choose_null_tip));
                }

                break;
            case R.id.tv_home_advice:
                UIUtil.showToastSafe(getString(R.string.yixi_tip));
                break;
            case R.id.tv_home_im:
                UIUtil.showToastSafe(getString(R.string.live_chat_room));
                break;
            case R.id.tv_home_custom:
                UIUtil.showToastSafe(getString(R.string.connect_customer));
                break;

        }
    }

    @Override
    public void showBanner(BannerBean bannerBean) {

        //banner
        if (null != bannerHome) {
            if (null != bannerBean && null != bannerBean.getRows()) {
                mBanners = bannerBean.getRows();
                if (null != mBanners && mBanners.size() > 0) {
                    bannerHome.setImages(mBanners);
                    bannerHome.start();
                }
            }

        }

    }

    @Override
    public void getDealRecordListSucess(int type, DealRecordListBean dealRecordListBean) {

        if (null != dealRecordListBean) {
            mRows = dealRecordListBean.getRows();

            switch (type) {
                case 0:
                    homeRecordAdapter.setmDatas(mRows);
                    homeRecordAdapter.notifyDataSetChanged();
                    break;
                case 1:
                    homeNewsAdapter.setmDatas(mRows);
                    homeNewsAdapter.notifyDataSetChanged();
                    break;
            }

        }
    }
}
